#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
#define MAX_BUF 1024
#define SERVER_PORT 9999
#define CLIENT_PORT 8888
int server_fd, flag = 1;

// 处理客户端请求
void *handle_client(void *arg)
{
    sleep(1);
    char read_buf[MAX_BUF];
    int read_size, ret;
    struct sockaddr_in client_addr = *(struct sockaddr_in *)arg;
    int addr_len = sizeof(client_addr);

    // 接受数据
    while (1)
    {
        memset(read_buf, 0, MAX_BUF);
        read_size = recvfrom(server_fd, read_buf, MAX_BUF, 0, (struct sockaddr *)&client_addr, &addr_len);
        if (read_size < 0)
        {
            perror("recv");
            break;
        }
        if (read_size == 0)
        {
            // 客户端断开连接
            printf("client disconnected\n");
            break;
        }
        if (strcmp(read_buf, "exit") == 0)
        {
            printf("对方退出\n");
            flag = 0;
            break;
        }

        printf("recv: %s\n", read_buf);
    }

    close(server_fd); // 关闭客户端套接字

    pthread_exit(NULL); // 退出线程
}

int main()
{

    int i, read_size, send_size;
    struct sockaddr_in server_addr, client_addr;
    pthread_t tid;
    char send_buf[MAX_BUF];
    int ret; // 返回值

    // 创建套接字
    server_fd = socket(AF_INET, SOCK_DGRAM, 0); // UDP
    if (server_fd < 0)
    {
        perror("socket");
        exit(1);
    }

    // 初始化server_addr
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY; // IP地址,接受所有ip地址

    // 绑定地址和端口
    ret = bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
    {
        perror("bind");
        close(server_fd);
        exit(1);
    }

    // 初始化client_addr
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(CLIENT_PORT);
    client_addr.sin_addr.s_addr = INADDR_ANY;

    int addr_len = sizeof(client_addr);

    // 创建子进程
    pthread_create(&tid, NULL, handle_client, &client_addr);

    // 发送数据
    while (1)
    {
        memset(send_buf, 0, MAX_BUF);
        read_size = read(0, send_buf, MAX_BUF);
        if (read_size < 0)
        {
            perror("read");
            close(server_fd);
            exit(1);
        }
        send_buf[read_size - 1] = '\0';

        if (flag == 0)
        {
            printf("已退出\n");
            break;
        }

        send_size = sendto(server_fd, send_buf, read_size, 0, (struct sockaddr *)&client_addr, addr_len);
        if (send_size < 0)
        {
            perror("send");
        }

        if (strcmp(send_buf, "exit") == 0)
        {
            printf("exit\n");
            break;
        }
    }

    close(server_fd); // 关闭服务器套接字

    return 0;
}